/*
 * @Author: ymp
 * @Date: 2019-12-10 14:40:55
 * @LastEditors: ${name}
 * @LastEditTime: 2019-12-16 11:36:47
 * @Description: 描述
 */
// 获取hostname
export const getHostname = () => window.location.hostname || ''

// 解析url
export const parseQuery = (url: string) => {
  const queryObj: Record<string, any> = {}
  const reg = /[?&]([^=&#]+)=([^&#]*)/g
  const querys = url.match(reg)
  if (querys) {
    for (const i in querys) {
      const query = querys[i].split('=')
      const key = query[0].substr(1)
      const value: any = query[1]
      queryObj[key] ? (queryObj[key] = [].concat(queryObj[key], value)) : (queryObj[key] = value)
    }
  }
  return queryObj
}

/**
 * url数据拼接
 *
 * @param {*} data
 * @returns
 */
export const formatUrlData = function(data: any) {
  let str = '',
    q = ''
  for (const i in data) {
    q = data[i]
    if (typeof data[i] === 'object') q = JSON.stringify(data[i])
    str += '&' + i + '=' + encodeURIComponent(q)
  }
  return str.substr(1)
}

export const assetUrlImg = (imgUrl: string) => {
  if (!imgUrl) return ''
  // base64
  if (imgUrl.indexOf('data:image') === 0) return imgUrl
  imgUrl = imgUrl.split(',')[0]
  if (imgUrl.indexOf('http') == 0) return imgUrl
  return 'https://assets.hzxituan.com/' + imgUrl
}

/**
 * 过滤cdn 图片
 * @param {*} value
 * @param {*} styleName
 */
export const formatImgUrl = function(value: string, styleName: string) {
  const url = assetUrlImg(value)
  if (!url.includes('?') && url.includes('assets.hzxituan.com') && styleName) {
    return `${url}?x-oss-process=style/${styleName}`
  }
  return url
}
